package com.wits.qso.web.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.web.Servlets;

import com.wits.platform.common.constants.ViewType;
import com.wits.platform.common.constants.WebConstants;
import com.wits.platform.common.utils.PageUtil;
import com.wits.platform.common.utils.StringUtil;
import com.wits.platform.web.controller.BaseController;
import com.wits.platform.web.mvc.PageParam;
import com.wits.qso.entity.Course;
import com.wits.qso.entity.CourseRegister;
import com.wits.qso.entity.CourseTeacherView;
import com.wits.qso.entity.Student;
import com.wits.qso.entity.Teacher;
import com.wits.qso.service.CourseRegisterService;
import com.wits.qso.service.CourseService;
import com.wits.qso.service.CourseTeacherViewService;
import com.wits.qso.service.StudentService;
import com.wits.qso.service.TeacherService;
import com.wits.qso.service.YearService;

@Controller
@RequestMapping(value = "qso/courseRegister")
public class CourseRegisterController extends BaseController {

	/**
	 * 注入courseRegisterService
	 */
	@Autowired
	private CourseRegisterService courseRegisterService;
	@Autowired
	private StudentService sutdentService;
	@Autowired
	private TeacherService teacherService;
	@Autowired
	private CourseService courseService;
	@Autowired
	private CourseTeacherViewService courseTeacherViewService;
	@Autowired
	private YearService yearService = null;

	@RequestMapping(value = "/toList")
	public String toList() {
		return "qso/courseRegister/list";
	}

	@RequestMapping(value = "/toSelect")
	public String toSelect() {
		return "qso/courseRegister/select";
	}

	@RequestMapping(value = "/toAuthList")
	public String toAuthList() {
		return "qso/courseRegister/authList";
	}

	/**
	 * 查询可以注册的课程列表（包含任课老师信息）
	 * 
	 * @param model
	 * @param page
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/listCTView")
	@ResponseBody
	public String listCourseTeachers(Model model,
			@ModelAttribute("page") PageParam page, HttpServletRequest req) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(
				req, "search_");
		// List<CourseTeacherView> crList = courseRegisterService
		// .findCourseTeacherViews(searchParams);
		Page<CourseTeacherView> crList = courseTeacherViewService
				.findCourseTeacherViewPage(searchParams, page);
		return PageUtil.toAjaxPageResult(crList);
	}

	/**
	 * 查询老师可以审核的学生注册记录列表，当前登录的用户（老师）与注册时的老师一致时才能够显示。
	 * 
	 * @param model
	 * @param page
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/authList")
	@ResponseBody
	public String authList(Model model, @ModelAttribute("page") PageParam page,
			HttpServletRequest req) {
		return list(model, page, req, "isTeacherAuth");
	}

	/**
	 * 加载课程注册列表页面，
	 * 
	 * @param model
	 * @param page
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public String list(Model model, @ModelAttribute("page") PageParam page,
			HttpServletRequest req) {
		return list(model, page, req, "isStudent");
	}

	/**
	 * 查询课程注册列表
	 * 
	 * @param model
	 * @param page
	 * @param req
	 * @param tag
	 *            标记
	 * @return
	 */
	private String list(Model model, @ModelAttribute("page") PageParam page,
			HttpServletRequest req, String tag) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(
				req, "search_");
		/**
		 * 如果是学生端查询，增加条件，只查询当前学生用户所注册过的记录,
		 */
		if ("isStudent".equals(tag)) {
			searchParams.put(SearchFilter.Operator.EQ + "_student.stuUserId",
					this.getCurrentUserId());
		}
		/**
		 * 如果是老师端查询，可以审核的记录，增加条件，当前登录的用户（老师）与注册时的老师一致时才能够显示。
		 */
		if ("isTeacherAuth".equals(tag)) {
			String status = req.getParameter("cr_status") == null ? "" : req
					.getParameter("cr_status");
			if (!"".equals(status)) {
				searchParams
						.put(SearchFilter.Operator.EQ + "_crStatus", status);
			}
			searchParams.put(SearchFilter.Operator.EQ + "_teacher.terUserId",
					this.getCurrentUserId());
		}
		Page<CourseRegister> listPage = courseRegisterService.findPage(
				CourseRegister.class, searchParams, page);
		return PageUtil.toAjaxPageResult(listPage.getTotalElements(),
				listPage.getContent());
	}

	@RequestMapping(value = "/toAuthView")
	public String toAgreeReject(Model model, @RequestParam String id) {
		model.addAttribute(WebConstants.COMMAND,
				courseRegisterService.getOne(id));
		return "qso/courseAuth/form";
	}

	@RequestMapping(value = "/toAgreeView")
	public String toAgreeView(Model model, @RequestParam String id) {
		model.addAttribute(WebConstants.COMMAND,
				courseRegisterService.getOne(id));
		return "qso/courseRegister/agreeForm";
	}

	@RequestMapping(value = "/toRejectView")
	public String toRejectView(Model model, @RequestParam String id) {
		model.addAttribute(WebConstants.COMMAND,
				courseRegisterService.getOne(id));
		return "qso/courseRegister/rejectForm";
	}

	/**
	 * 加载课程注册记录查看页面
	 * 
	 * @param model
	 * @param viewType
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/view/{viewType}")
	public String toView(Model model, @PathVariable String viewType,
			@RequestParam String id) {
		if (ViewType.Add.getView().equals(viewType)) {
			model.addAttribute(WebConstants.COMMAND, new CourseRegister());
		} else {
			model.addAttribute(WebConstants.COMMAND,
					courseRegisterService.getOne(id));
		}
		model.addAttribute("viewType", viewType);
		return "qso/courseRegister/form";
	}

	/**
	 * 保存提交的新增或修改注册申请记录
	 * 
	 * @param model
	 * @param command
	 * @param viewType
	 * @param result
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/save", method = { RequestMethod.POST })
	@ResponseBody
	public Object save(Model model,
			@ModelAttribute("command") @Valid CourseRegister command,
			@RequestParam String viewType, BindingResult result,
			HttpServletRequest req) {
		if (result.hasErrors()) {
			model.addAttribute(WebConstants.COMMAND, command);
			return toView(model, viewType, command.getId());
		}

		// if (command.getDateF().compareTo( command.getDateT() ) > 0) {
		// return ajaxDoneError( "结束时间不能早于开始时间" );
		// }
		// Year enabledYear = yearService.findEnabled();

		// if (null == enabledYear) {
		// return ajaxDoneError( "请设定学期" );
		// } else {
		// if ( enabledYear.getDateF().compareTo( command.getDateF() ) > 0 ||
		// enabledYear.getDateT().compareTo( command.getDateT() ) < 0 ) {
		// return ajaxDoneError( "开始(结束)时间超出所设定学期时间" );
		// }
		// }

		
		try {
			Student student = sutdentService.findByUserId(getCurrentUserId());
			// String stuId = student == null || student.getStuId() == null ? ""
			// : student.getStuId();
			// command.setStuId(stuId);
			command.setStudent(student);
			String terId = req.getParameter("terId") == null ? "" : req
					.getParameter("terId");
			Teacher teacher = teacherService.getOne(terId);
			command.setTeacher(teacher);

			String courseId = req.getParameter("courseId") == null ? "" : req
					.getParameter("courseId");
			Course course = courseService.getOne(courseId);
			command.setCourse(course);

			// 先判断是否存在，已经注册，正在注册
			boolean isReg =false;
			if (ViewType.Add.getView().equals(viewType)) {
				command.setDateCre(new Date());
				command.setUserCre(getCurrentUserId());
				isReg=isRegister(1, command);
			} else if (ViewType.Modify.getView().equals(viewType)) {
				command.setDateUpd(new Date());
				command.setUserUpd(getCurrentUserId());
				isReg=isRegister(2, command);
			}
			if (isReg) {
				String courseName = course != null && course.getTitle() != null ? course
						.getTitle() : "";
				return ajaxDoneError("已经存在 " + courseName
						+ " 这门课程的注册申请记录，请检查提交的信息！");
			}

			courseRegisterService.save(command);
			return ajaxDoneSuccess(this.getText("save.success"));
		} catch (Exception e) {
			return ajaxDoneError(this.getText("save.failed"), e);
		}
	}

	/**
	 * 删除课程注册记录
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(String ids) {
		boolean hasSusscesed = false;
		boolean hasErrored = false;

		for (String id : Arrays.asList(StringUtil.split(ids, ","))) {
			try {
				courseRegisterService.delete(id);
				hasSusscesed = true;
			} catch (Exception e) {
				hasErrored = true;
			}
		}

		if (hasSusscesed) {
			if (hasErrored) {
				return ajaxDoneError("有些被引用的课程无法删除");
			} else {
				return ajaxDoneSuccess(this.getText("delete.success"));
			}
		} else {
			return ajaxDoneError("所选课程已被引用, 无法删除");
		}
		// try {
		// courseService.deleteInBatch(Arrays.asList(StringUtils.split(ids,
		// ",")));
		// return ajaxDoneSuccess(this.getText("delete.success"));
		// } catch (Exception e) {
		// return ajaxDoneError(this.getText("delete.failed"),e);
		// }
	}

	/**
	 * 申请注册课程记录
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/doApply")
	@ResponseBody
	public Object doApply(String ids) {
		return updateStatus(ids, 2);
	}

	/**
	 * 同意注册课程记录
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/doAgree", method = { RequestMethod.POST })
	@ResponseBody
	// public Object doAgree(@RequestParam("id") String id,
	// @RequestParam("crMessage") String message) {
	public Object doAgree(Model model,
			@ModelAttribute("command") @Valid CourseRegister command,
			BindingResult result, HttpServletRequest req) {
		String id = command.getId();
		String message = command.getCrMessage();
		return agreeReject(id, message, 1);
	}

	/**
	 * 拒绝注册课程记录
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/doReject", method = { RequestMethod.POST })
	@ResponseBody
	// public Object doReject(@RequestParam("id") String id,
	// @RequestParam("crMessage") String message) {
	public Object doReject(Model model,
			@ModelAttribute("command") @Valid CourseRegister command,
			BindingResult result, HttpServletRequest req) {
		String id = command.getId();
		String message = command.getCrMessage();
		return agreeReject(id, message, 2);
	}

	/**
	 * 修改状态
	 * 
	 * @param ids
	 * @param type
	 *            1新增录入2提交注册
	 * @return
	 */
	private Object updateStatus(String ids, int type) {
		boolean hasSusscesed = false;
		boolean hasErrored = false;

		String status = "";
		String text = "";
		for (String id : Arrays.asList(StringUtil.split(ids, ","))) {
			try {
				switch (type) {
				case 1:
					status = "ED";
					text = "无法改为新建状态";
					break;
				case 2:
					status = "AP";
					text = "课程无法成功注册";
					break;
				}
				CourseRegister obj = courseRegisterService.getOne(id);
				// 先判断是否注册过
				boolean isReg = isRegister(3, obj);
				if (isReg) {
					String courseName = obj != null && obj.getCourse() != null
							&& obj.getCourse().getTitle() != null ? obj
							.getCourse().getTitle() : "";
					return ajaxDoneError("已经注册过 " + courseName
							+ " 这门课程，不能重复注册！");
				}
				courseRegisterService.modifyStatus(id, status);
				hasSusscesed = true;
			} catch (Exception e) {
				hasErrored = true;
			}
		}

		if (hasSusscesed) {
			if (hasErrored) {
				return ajaxDoneError(text);
			} else {
				return ajaxDoneSuccess("成功");
			}
		} else {
			return ajaxDoneError(text);
		}
	}

	private Object agreeReject(String id, String message, int type) {
		boolean hasErrored = false;

		String text = "";
		try {
			switch (type) {
			case 1:
				text = "同意注册申请失败";
				courseRegisterService.doAgree(id, message);
				break;
			case 2:
				text = "拒绝注册申请失败";
				courseRegisterService.doReject(id, message);
				break;
			}
			hasErrored = false;
		} catch (Exception e) {
			hasErrored = true;
		}
		if (hasErrored) {
			return ajaxDoneError(text);
		} else {
			return ajaxDoneSuccess("成功");
		}

	}

	/**
	 * 唯一检查
	 * 
	 * @param id
	 * @param oldId
	 * @return
	 */
	@RequestMapping(value = "/checkUniqueId")
	@ResponseBody
	public boolean checkUniqueId(@RequestParam("id") String id,
			@RequestParam("oldId") String oldId) {
		if (id.equals(oldId)) {
			return true;
		}
		CourseRegister obj = courseRegisterService.getOne(id);
		return obj == null;
	}

	/**
	 * 查询当前学生已经注册的课程，并与新增和修改的注册课程比较， 如果新增和修改的是已经注册过的，提示不能重复注册
	 * 
	 * @param optionType
	 *            操作类型 1新增 2修改，3在提交申请时进行判断
	 * @param cr
	 *            尚未保存至数据库的注册记录
	 * @return 存在相同记录返回true
	 */
	private boolean isRegister(int optionType, CourseRegister cr) {
		boolean res = false;
		// 查询当前学生已经注册成功的课程，list为空，则返回没有注册过，
		Map<String, Object> searchParams = new HashMap<String, Object>();
		/**
		 * 如果是学生端查询，增加条件，只查询当前学生用户所填写、注册过的记录,
		 */
		searchParams.put("stu_user_id", this.getCurrentUserId());
		if (1 == optionType|| 2 == optionType) {
			searchParams.put("cr_in_status", " 'ED', 'AP', 'CO', 'DL' ");
		} else if (3 == optionType) {
			searchParams.put("cr_status", "CO");
		}
		List<CourseRegister> courseRegisterList = courseRegisterService
				.findCourseRegisters(searchParams);
		// list不为空，则逐一比较，
		if (courseRegisterList != null) {
			// 新增 ，如果存在与当前填入的课程一致的注册成功记录，就返回已经注册过，如果循环完毕
			// 仍然没有发现，则返回没有注册过
			if(1==optionType){
				for (int i = 0; i < courseRegisterList.size(); i++) {
					CourseRegister tmp = courseRegisterList.get(i);
					if (tmp != null
							&& cr != null
							&& cr.getCourse() != null
							&& tmp.getCourse() != null
							&& cr.getCourse().getId() != null
							&& cr.getCourse().getId()
									.equals(tmp.getCourse().getId())) {
						res = true;
						break;
					}
				}
			}else if(2==optionType||3==optionType){
				// 修改，排除当前正在操作的记录(已经保存至数据库的记录)，如果list中还存在和当前未保存记录相同
				// 的，则返回已经存在，否则返回不存在。
				// 修改与提交申请的判断条件合二为一
				for (int i = 0; i < courseRegisterList.size(); i++) {
					CourseRegister tmp = courseRegisterList.get(i);
					if (tmp != null
							&& cr != null
							&& cr.getCourse() != null
							&& tmp.getCourse() != null
							&& cr.getCourse().getId() != null
							&& !tmp.getId().equals(cr.getId())
							&& cr.getCourse().getId()
									.equals(tmp.getCourse().getId())) {
						res = true;
						break;
					}
				}
			}
			
		}

		return res;
	}
}
